import yaml
from flask import Flask,request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import *
from sqlalchemy.orm import Session
from back_live1.utils.log_utils import logger
from flask_jwt_extended import create_access_token
from flask_jwt_extended import current_user
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager

from hmac import compare_digest

app = Flask(__name__)

# 初始化数据库
with open("./data/data.yaml") as f:
    result = yaml.safe_load(f)
    username = result.get("database").get('username')
    password = result.get("database").get('password')
    server = result.get("database").get('server')
    db = result.get("database").get('db')

app.config["JWT_SECRET_KEY"] = "super-secret"
app.config['SQLALCHEMY_DATABASE_URI'] = \
    f"mysql+pymysql://{username}:{password}@{server}/{db}?charset=utf8"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

jwt = JWTManager(app)
db = SQLAlchemy(app)
db_session:Session = db.session

# 用户表
class UserDo(db.Model):
    # 定义表名
    __tablename__ = 'user'

    # 定义表字段
    id = Column(Integer, primary_key=True)
    username = Column(String(20), unique=True)
    password = Column(String(255))

    def as_dict(self):
        # 用户对象转换为字典
        return {"id":self.id,"username":self.username,"password":self.password}

    # 检验密码
    def check_password(self, password):
        return compare_digest(password, self.password)

# 配置用户验证的条件
@jwt.user_lookup_loader
def user_lookup_callback(_jwt_header, jwt_data):
    logger.debug(f"_jwt_header {_jwt_header}")
    logger.debug(f"jwt_data {jwt_data}")
    # 拿到用户名
    identity = jwt_data["sub"]["username"]
    # 通过用户名到数据库中查询用户是否存在
    return UserDo.query.filter_by(username=identity).one_or_none()


@app.route("/login",methods=["post"])
def login():
    # 拿到请求信息
    user_info = request.json
    logger.debug(f"请求数据为：{user_info}")
    # 获取用户名
    username = user_info.get("username")
    # 获取密码
    password = user_info.get("password")
    logger.info(f"获取到的用户名为{username},密码为：{password}")
    # 用户名为空
    if not username:
        return {"code":40011,"msg":"username is none"}
    # 密码为空
    if not password:
        return {"code":40012,"msg":"password is none"}
    # 通过用户名和密码生成 user 对象
    user = UserDo(username=username,password=password)
    logger.debug(f"生成的 user 对象为：{user}")
    try:
        #  通过用户名查询用户是否存在
        user_result = db_session.query(UserDo).filter_by(username=user.username).first()
        logger.debug(f"通过用户名：{user.username} 查询的结果为 {user_result}")
    #     如果用户名不存在
        if not user_result:
            return {"code":40013,"msg":"user is not register"}
    #     用户存在，密码错误
        if not user_result.check_password(password):
            return {"code":40014,"msg":"password is wrong"}
    #     如果用户存在 生成token
        token = create_access_token(identity=user_result.as_dict())
        logger.debug(f"生成的 token {token}")
        # token 生成成功
        if token:
            return {"code":0,"msg":"success","token":token}
        # token 生成失败
        else:
            return {"code":40021,"msg":"login error"}
    except Exception as e:
        logger.debug((e))
        return {"code":40021,"msg":"login error"}

@app.route("/testcase")
# token 鉴权
@jwt_required()
def get_testcase():

    return {"code":0,"msg":"success"}

if __name__ == '__main__':
    # db.create_all()
    # db.session.add(UserDo(username='lily',password='123456'))
    # db.session.commit()
    app.run(debug=True)